﻿App.Product = function() {

    return {

        currentFormValues: {},

        getStore: function() {
            var store = new Ext.data.DirectStore({
                directFn: ProductAction.pagedQuery,
                paramOrder: "start,limit,sort,dir,query",
                paramNames: {
                    start: "start",
                    limit: "limit",
                    dir: "dir",
                    sort: "sort",
                    query: "query"
                },
                baseParams: {
                    dir: "",
                    sort: "",
                    start: 0,
                    limit: 50,
                    query: ""
                },
                paramsAsHash: true,
                totalProperty: 'totalCount',
                idProperty: 'id',
                root: 'result',
                autoLoad: true,
                remoteSort: true,
                fields: [{
                    name: 'id',
                    type: 'int'
                },
                {
                    name: 'name'
                },
                {
                    name: 'spec'
                },
                {
                    name: 'price',
                    type: 'float'
                }]
            });
            return store;
        },

        getForm: function() {
            var frm = new Ext.form.FormPanel({
                labelAlign: 'left',
                buttonAlign: 'center',
                bodyStyle: 'padding:5px',
                frame: true,
                labelWidth: 80,
                defaultType: 'textfield',
                defaults: {
                    allowBlank: false,
                    anchor: '90%',
                    enableKeyEvents: true
                },
                items: [{
                    xtype: 'hidden',
                    name: 'id',
                    value: ''
                },
                {
                    name: 'code',
                    fieldLabel: '产品编号',
                    maxlength: 20,
                    maskRe: /[A-Za-z0-9]/,
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                var obj = this.frm.form.findField("name");
                                if (obj) obj.focus();
                            }
                        } //keypress
                    }
                },
                {
                    name: 'name',
                    fieldLabel: '产品名称',
                    maxlength: 200,
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                var obj = this.frm.form.findField("spec");
                                if (obj) obj.focus();
                            }
                        } //keypress
                    }
                },
                {
                    name: 'spec',
                    fieldLabel: '产品规格',
                    maxlength: 100,
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                var obj = this.frm.form.findField("price");
                                if (obj) obj.focus();
                            }
                        } //keypress
                    }
                },
                {
                    name: 'price',
                    fieldLabel: '单价',
                    maskRe: /[0-9\.]/,
                    regex: /^([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/,
                    regexText: "请输入正确的单价",
                    listeners: {
                        scope: this,
                        keypress: function(field, e) {
                            if (e.getKey() == 13) {
                                this.submit();
                            }
                        } //keypress
                    }
                }],
                //items
                buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        this.frm.form.reset();
                        this.frm.form.setValues(this.currentFormValues);
                        this.frm.form.clearInvalid();
                    }
                }] //buttons
            }); //FormPanel
            return frm;
        },

        submit: function() {
            if (this.frm.form.isValid()) {
                var id = this.frm.form.findField("id").getValue();
                this.frm.form.api = {
                    submit: ProductAction.save
                };
                this.frm.form.doAction("directsubmit", {
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                        var msg = "";
                        if (action.result.success) {
                            this.store.reload();
                            if (action.result.method == "Create") {
                                this.frm.form.reset();
                                msg = "新产品已保存。";
                            } else {
                                this.dlg.hide();
                                msg = "产品已更新。";
                            }
                        }
                        Ext.Msg.alert('信息', msg);
                    },
                    failure: function(form, action) {
                        if (action.result && action.result.msg) {
                            Ext.Msg.alert('错误', action.result.msg);
                        }
                        if (action.message) {
                            Ext.Msg.alert('错误', action.message);
                        }
                    }
                });
            }
        },

        getDialog: function() {
            var dlg = new Ext.Window({
                width: 400,
                height: 300,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.frm],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.frm.form.waitMsgTarget = fp.getEl();
                    },
                    show: function() {
                        this.frm.form.setValues(this.currentFormValues);
                        this.frm.form.clearInvalid();
                    }
                }
            }); //dlg
            return dlg;
        },

        highLight: function(value) {
            var key = App.Product.grid.store.baseParams.query;
            var v = value ? value.toString() : '';
            if (Ext.isString(v) & Ext.isString(key)) {
                if (key.length > 0) {
                    var re = new RegExp(key, "g");
                    return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
                } else {
                    return v
                }
            } else {
                return v;
            }
        },

        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.CheckboxSelectionModel();

            this.grid = new Ext.grid.GridPanel({
                tbar: new Ext.PagingToolbar({
                    pageSize: 50,
                    displayInfo: true,
                    store: this.store,
                    items: ['-', {
                        text: '增加',
                        scope: this,
                        handler: this.add
                    },
                    {
                        text: '编辑',
                        scope: this,
                        handler: this.edit
                    },
                    {
                        text: '删除',
                        scope: this,
                        handler: this.del
                    },
                    '-', new Ext.ux.form.SearchField({
                        store: this.store,
                        width: 110
                    })]
                }),
                store: this.store,
                sm: sm,
                columns: [sm, {
                    header: "编号",
                    width: 100,
                    sortable: true,
                    dataIndex: 'id'
                },
                {
                    header: "产品名称",
                    width: 150,
                    sortable: true,
                    dataIndex: 'name',
                    renderer: this.highLight
                },
                {
                    header: "产品规格",
                    width: 300,
                    sortable: true,
                    dataIndex: 'spec',
                    renderer: this.highLight
                },
                {
                    header: "单价",
                    width: 200,
                    sortable: true,
                    dataIndex: 'price',
                    align: 'right',
                    renderer: function(v) {
                        return Ext.util.Format.number(v, "0.00");
                    }
                }]
            });

            panel.add(this.grid);

        },

        add: function() {
            Ext.apply(this.currentFormValues, {
                id: '',
                code: "",
                name: "",
                spec: "",
                price: '0'
            });
            this.dlg.setTitle("增加产品");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑产品");
                var rec = this.grid.getSelectionModel().getSelected();
                Ext.apply(this.currentFormValues, {
                    id: rec.data.id,
                    code: rec.data.id,
                    name: rec.data.name,
                    spec: rec.data.spec,
                    price: rec.data.price
                });
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的产品。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelections();
                var ids = [];
                var titles = '';
                for (var i = 0; i < recs.length; i++) {
                    var data = recs[i].data;
                    ids.push(data.id);
                    titles += data.name + '<br>';
                }
                Ext.Msg.confirm('删除产品', '确定删除以下产品？<br><font color="red">' + titles + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        ProductAction.remove(ids.toString(),
                        function(data, e) {
                            if (data) {
                                if (data.success) {
                                    Ext.Msg.alert('信息', '已成功删除产品。');
                                    App.Product.store.reload();
                                } else {
                                    Ext.Msg.alert('信息', data.msg);
                                }
                            } else {
                                Ext.Msg.alert('信息', e.msg);
                            }
                        })
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的产品！');
            }
        },

        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            }; //if(!this.store)
            if (!this.frm) {
                this.frm = this.getForm();
            }; //if(!this.frm)

            if (!this.dlg) {
                this.dlg = this.getDialog();
            }; //if(!this.dlg)
            this.createGrid(id);

        }

    }; //return
} (); //function
